import config from '../../config.js'
import request from '../request.js'
import common from '../common.js'

let mpWeixin = {}

/**
 * 小程序获取OPENID
 * @date 2020-11-18
 */
mpWeixin.getOpenid = function() {
	let openid = uni.getStorageSync('openid')
	let user_id = uni.getStorageSync('user_id')

	return new Promise((resolve, reject) => {
		if (!openid) {
			mpWeixin.login().then(res => {
				resolve(res)
			}).catch(res => {
				reject()
			})
		} else {
			// 检查登录态  wx.checkSession  session_key如果失效，需要重新执行登录流程
			uni.checkSession({
				success(res) {
					// console.log('checkSessionSuccess')
					resolve({
						openid: uni.getStorageSync('openid'),
						user_id: uni.getStorageSync('user_id'),
					})
					console.log('生产环境 缓存:openid = ' + uni.getStorageSync('openid') +
						' user_id = ' + uni
						.getStorageSync('user_id'))
				},
				fail(err) {
					// console.log('checkSessionFail')
					mpWeixin.login().then(res => {
						resolve(res)
					}).catch(res => {
						reject()
					})
				}
			})

		}
	})
}

mpWeixin.login = function() {
	return new Promise((resolve, reject) => {
		uni.getProvider({
			service: 'oauth',
			success: function(res) {
				if (~res.provider.indexOf('weixin')) {
					uni.login({
						provider: 'weixin',
						success: function(loginRes) {
							reject()
							return
							request.getData(
								'base/mpweixin/api/Auth/getOpenid', {
									code: loginRes.code
								}, {
									loading: 1
								}).then(res => {
								uni.setStorageSync('openid', res.data
									.openid)
								uni.setStorageSync('user_id', res
									.data.user_id)
								uni.setStorageSync('access_token',
									res.data.access_token)
								uni.setStorageSync(
									'access_token_expire_time',
									res.data
									.access_token_expire_time)

								resolve({
									openid: uni
										.getStorageSync(
											'openid'),
									user_id: uni
										.getStorageSync(
											'user_id'),
								})

								console.log('生产环境刚获得 刚获得:openid = ' +
									uni.getStorageSync(
										'openid') +
									' user_id = ' +
									uni.getStorageSync(
										'user_id'))
							}, err => {
								console.log(err)
								reject()
							})
						}
					})
				}
			}
		})
	})
}

export default mpWeixin
